import React, { useEffect, useState } from 'react'
import './Detail.css'
import { List, Button, Picker, SwipeAction, Image, Popup, Selector, Dialog } from 'antd-mobile'
import { AppstoreOutline } from 'antd-mobile-icons'
import basicColumns from '../../components/Times/TimeWekk'
import '../../components/Times/calendar.css'
import ajax from '../../api/ajax'
import { AlterItemChange } from '../../redux/WriteSlice/WriteSlice'
import { typeDetailChange } from '../../redux/DetailSlice/DetailSlice'
import { DetailDelete } from '../../redux/DetailSlice/DetailSlice'
import { DetailGetAsync } from '../../redux/DetailSlice/DetailSlice'

// 图片
import pit2 from '../../img/2.png'
import { useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'

export default function Detail() {
    // 时间年份
    const [timeValue, setTimeValue] = useState(['2023年', '6月'])
    const [visible1, setVisible1] = useState(false)
    const [visible2, setVisible2] = useState(false)
    const [visible3, setVisible3] = useState(false)
    // 类型
    const [visible4, setVisible4] = useState(false)
    // 总金额 
    const [sumInput, setSumInput] = useState(0.00)
    const [sumOutput, setSumOutput] = useState(0.00)
    const navigate = useNavigate()
    let pitUrl ='https://images.unsplash.com/photo-1548532928-b34e3be62fc6?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ'
    const pitAll={
        '食品酒水': 'https://i.postimg.cc/Qdj9dvBz/image.jpg',
        '行车交通': 'https://i.postimg.cc/HnWRxYgx/image.png',
        '居家物业': 'https://i.postimg.cc/nzpwRFMk/image.jpg',
    }
    const rightActions = [
        {
            key: 'unsubscribe',
            text: '修改',
            color: 'primary',
        },
        {
            key: 'delete',
            text: '删除',
            color: 'danger',
        },
    ]
    const dispatch = useDispatch();
    const userDetail = useSelector(state => state.DetailSliceReducer.userDetail2);
    const typeDetail = useSelector(state => state.DetailSliceReducer.typeDetail);
    // 要显示都数据
    const [newVal, setNewVal] = useState([])
    // 转换后的新数据
    const [oldVal, setOldVal] = useState([])


    // 要显示的类型
    const [options, setOptions] = useState([])
    // 获取类型
    useEffect(() => {
        setOptions(typeDetail)
    }, [typeDetail, options])

    // 获取转化后的初始数据,并进行转化
    useEffect(() => {
        // 请求类型的数据
        // axios.post('').then(res => {
        //     DetailGetAsync(res.data)
        // })
        // 查找是否存在相同日期
        const SameTime = (all, val) => all.every(item => item.time !== val.time)
        // 将数据转换一下
        const userDetailChange = () => {
            let x = {
                time: '',
                sumPrice1: 0,
                sumPrice2: 0,
                value: [{
                    id: '',
                    time: '',
                    type: [],
                    billType: 1,
                    remark: 'Deserunt dolor ea eaque eos',
                    avatar: 'https://images.unsplash.com/photo-1548532928-b34e3be62fc6?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ',
                    shopName: 'A',
                }]
            }
            // 转换后的新数据

            let all = []
            
            userDetail.map(val => {
                // sumPrice1是收入 sumPrice2是支出
                let sumPrice1 = 0
                let sumPrice2 = 0
                // 判断是否是第一个数据，或者其他新的日期数据
                if (all.length === 0 || SameTime(all, val)) {
                    // 如果0只支出，1是收入
                    val.billType === 0 ? sumPrice2 = val.money : sumPrice1 = val.money
                    let value = []
                    value.push({
                        ...x.value[0],
                        ...val
                    })
                    all.push({
                        ...x,
                        time: val.time,
                        sumPrice1,
                        sumPrice2,
                        value: value
                    })
                } else {
                    // 否则已经相同时间日期
                    all = all.map(item => {
                        if (item.time === val.time) {
                            // 如果0只支出，1是收入
                            val.billType === 0 ? item.sumPrice2 += val.money : item.sumPrice1 += val.money
                            item.value.push({
                                ...x.value[0],
                                ...val
                            })
                        }
                        return item

                    })
                }
                return
            })
            all.sort((a, b) => {
                let x = Number(a.time.substring(a.time.indexOf('月') + 1, a.time.indexOf('日')))
                let y = Number(b.time.substring(b.time.indexOf('月') + 1, b.time.indexOf('日')))
                return x - y
            })
            // console.log('all',all);
            setOldVal(all)
        }
        userDetailChange()
    }, [userDetail])

    //更新要展示的数据
    useEffect(() => {
        typeChangeDetail(typeDetail)
    }, [oldVal])



    // 判断类型是否被选中
    function typeIfTrue(newOptions,typeVal) {
        let type = false
        newOptions.map(item => {
            if (item.value === typeVal[0]) {
                type = item.children.some(items => {
                    return items.value === typeVal[1] && items.mark
                })
            }
        })
        return type
    }


    // 根据类型变化更新数据
    function typeChangeDetail(newOptionsX) {
        let x = oldVal.filter(item => item.value.filter(items => typeIfTrue(newOptionsX, items.type)).length > 0)
        let timeChar = timeValue[0] + timeValue[1]
        x = x.filter(item => item.time.includes(timeChar))
        // 每个月的金额
        let sumPrice1=0
        let sumPrice2=0
        x.map(item=>{
            sumPrice1 = parseFloat(sumPrice1) + parseFloat(item.sumPrice1)
            sumPrice2 = parseFloat(sumPrice2) + parseFloat(item.sumPrice2)
        })
        setSumInput(sumPrice1)
        setSumOutput(sumPrice2)
        setNewVal(x)
    }
    // 根据日期变化更新数据
    function timeChangeDetail(time) {

        let timeChar=time[0]+time[1]
        let x = oldVal.filter(item => item.value.filter(items => typeIfTrue(options, items.type)).length > 0)
        x = x.filter(item => item.time.includes(timeChar))
        // 每个月的金额
        let sumPrice1 = 0
        let sumPrice2 = 0
        x.map(item => {
            sumPrice1 = sumPrice1 + item.sumPrice1
            sumPrice2 = sumPrice2 + item.sumPrice2
        })
        setSumInput(sumPrice1)
        setSumOutput(sumPrice2)
        setNewVal(x)
    }

    // 更新被选中的类型
    const typeChange = (val, item) => {
        let newItem = item.children.map(x => {
            // 对被选中数组遍历，将未选择的置为false
            // val.some(y => x.label === y)如果为真，则说明被选中，反之为被选中
            let mark
            if (val.some(y => x['label'] === y)) {
                // x['mark'] = true
                mark = true
            } else {
                // x['mark'] = false
                mark = false
            }
            return { ...x, mark }
        })
        let newOptionsX = options.map(x => {
            // 查找修改的是哪一项item，然后更新
            let children = x['children']
            if (x['label'] === item['label']) {
                children = newItem
            }
            return { ...x, children }
        })
        // 改变store里的数据
        dispatch(typeDetailChange(newOptionsX))
        
        // 因为类型改变，使显示的数据改变，（方法）
        typeChangeDetail(newOptionsX)
    }


    // 修改和删除功能
    const actionChange = async (action, value) => {
        if (action.text === '修改') {
            dispatch(AlterItemChange({ ...value, fun: '修改' }))
            navigate(`/home/Alter/${value.id}`)
        } else {
            const result = await Dialog.confirm({ content: '确定要删除吗？' })
            if (result){
                // 删除数据
                const newItem = newVal.map(item => {
                    item.value = item.value.filter(items => items.id !== value.id)
                    return item
                })
                dispatch(DetailDelete(value.id))
                setNewVal(newItem)
            }

            // 向服务器发请求删除数据
            // console.log('value', value);
            const data = await ajax.post('/bill/deleteBill', {id:value.id})
            if (data.msg === 'success') {
                console.log('服务器删除请求完成');
            }
        }
    }
    return (
        <div className='Detail'>
            <div className='DetailTop'>
                <p className='DetailTopTitle'>
                    <span>简记账</span>
                    <Button
                        onClick={() => {
                            setVisible1(true)

                        }}
                        className='select'>
                        支付宝
                    </Button>
                    <Button
                        onClick={() => {
                            setVisible2(true)
                        }}
                    >
                        微信
                    </Button>
                </p>
                <div className='DetailTopType'>
                    <div>
                        <Button
                            onClick={() => {
                                setVisible4(true)
                            }}
                        >
                            <span>全部类型</span>
                            <AppstoreOutline />
                        </Button>
                        {/* 类型 */}
                        <Popup
                            visible={visible4}
                            showCloseButton
                            onClose={() => {
                                setVisible4(false)
                            }}
                            onMaskClick={() => {
                                setVisible4(false)
                            }}
                        >
                            <div
                                style={{ height: '40vh', overflowY: 'scroll', padding: '10px 20px' }}
                            >

                                {
                                    options.map(item => {
                                        let x = item.children.map(items => {
                                            if (items.mark) return items.value
                                        })
                                        return <div className='DetailTopTypeContent' key={item.label}>
                                            <span className='DetailTopTypeTitle'>
                                                {item.label}
                                                <Image
                                                    // src={v.avatarv == null ? pitUrl : v.avatarv}
                                                    src={pitAll[item.label]}
                                                    style={{ borderRadius: 20 }}
                                                    fit='cover'
                                                    width={40}
                                                    height={40}
                                                />
                                            </span>
                                            <Selector
                                                columns={3}
                                                options={item.children}
                                                defaultValue={x}
                                                multiple={true}
                                                onChange={(value) => typeChange(value, item)}
                                                style={{
                                                    '--border-radius': '80px',
                                                    '--border': 'solid transparent 1px',
                                                    '--checked-border': 'solid var(--adm-color-primary) 1px',
                                                    '--padding': '8px 4px',
                                                }}
                                            />
                                        </div>
                                    })
                                }
                            </div>
                        </Popup>
                        <br></br>
                        <div className='DetailTopTime'>
                            <Button
                                onClick={() => {
                                    setVisible3(true)
                                    
                                }}
                            >
                                {/* 年份时间 */}
                                {timeValue}
                            </Button>
                            <Picker
                                columns={basicColumns}
                                visible={visible3}
                                onClose={() => {
                                    setVisible3(false)
                                }}
                                value={timeValue}
                                onConfirm={v => {
                                    setTimeValue(v)
                                    timeChangeDetail(v)
                                }}
                            />
                        </div>
                    </div>
                    <div className='DetailTopTypeCost'>
                        <div>
                            <span>总收入:</span>
                            <span>{sumInput + '元'}</span>
                        </div>
                        <div>
                            <span>总支出:</span>
                            <span>{sumOutput+'元'}</span>
                        </div>
                    </div>

                </div>
            </div>
            <div className='DetailContain2'>
                <div>
                    {
                        newVal.map((item, index) =>
                            <List header={
                                <div>
                                    <span>{item.time}</span>
                                    <span>出<i>{item.sumPrice2}</i></span>
                                    <span>入<i>{item.sumPrice1}</i></span>

                                </div>
                            } key={index}>
                                {
                                    item.value.map((v, index) =>
                                        <SwipeAction
                                            key={index}
                                            rightActions={rightActions}
                                            onAction={(action) => actionChange(action, v)}
                                        >
                                            <List.Item
                                                extra={v.billType === 0 ? '-' + v.money : '+' + v.money}
                                                key={v.id ? v.id : v.IdTime}
                                                prefix={
                                                    <Image
                                                        // src={v.avatarv == null ? pitUrl : v.avatarv}
                                                        src={pitAll[v.type[0]]}
                                                        style={{ borderRadius: 20 }}
                                                        fit='cover'
                                                        width={40}
                                                        height={40}
                                                    />
                                                } 
                                                description={(v.shopName == null ? '无商家名' : v.shopName) + ':' + (v.remark == null ? '无备注' : v.remark)}
                                            >
                                                {v.type[0] + '>' + v.type[1]}
                                            </List.Item>
                                        </SwipeAction>)
                                }

                            </List>)
                    }

                </div>
            </div>
        </div>
    )
}
